import { login, getUserInfo, getUserDetail } from '@/api/user'
import { setToken, getToken, removeToken, setTime } from '@/utils/auth'
import { resetRouter} from '@/router'
const state ={
  token: getToken(), // 获取token
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token  // token存vuex
    setToken(token)     // token存Cookie
    setTime(Date.now()) // 存储当前时间戳
  },
  removeToken(state) {  // 退出登录, vuex里token为空 , cookie里清除token
    state.token = ''
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  },
  updatePhoto(state, photo){
    state.userInfo.staffPhoto=photo
  }

}
const actions = {
  async login({commit}, data) {  // 解构了context
    const token = await login(data)
    commit('setToken', token)
  },
  async getUserInfo({commit}) {
    const res = await getUserInfo()
    const res2 = await getUserDetail(res.userId)
    // res2.staffPhoto = 'adcxc.jpg' // 实验图片失效替换成默认图片
    const result = {...res,...res2}
    commit('setUserInfo', result)
    return result // 配置动态路由
  },
  logout({commit}) {
    // 1. 移除vuex个人信息
   commit('removeToken')
     // 2. 移除token信息
   commit('removeUserInfo')
   // 3. 重置路由
   resetRouter()
   // 4. 重置 vuex 中的路由信息
   commit('permission/setRoutes', [], {root: true}) // root : true 从根命名空间找
   // 重置主题颜色
   commit('settings.resetTheme', null ,{ root:trueyjgjygjjhghjtu76ivykvuhjvyku})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

